
package com.crowdfunding.circle.news.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crowdfunding.circle.common.controller.BaseController;
import com.crowdfunding.circle.common.param.SessionUserInfo;
import com.crowdfunding.circle.news.entity.NewsInfoVO;
import com.crowdfunding.circle.news.param.NewsInfoParam;
import com.crowdfunding.circle.news.service.NewsInfoService;

/**
 * 新闻Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class NewsInfoController extends BaseController {
    
    private Logger logger = LoggerFactory.getLogger(NewsInfoController.class);
    
    @Autowired
    private NewsInfoService newsInfoService;
    
    private final static String LIST_PAGE = "/news/news_list_ajax";
    
    private final static String QUERY_LIST_PAGE = "/news/news_list";
    
    private final static String VIEW_PAGE = "/news/news_view";
    
    private final static String UPDATE_PAGE = "/news/news_edit";

    private static final String ADMIN_MANAGE_PAGE = "/admin/news_manage";
    
    @RequestMapping(value = "/uncheck/news/list_page")
    public ModelAndView newsList(NewsInfoParam newsInfoParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("paramMap", newsInfoParam);
        return new ModelAndView(QUERY_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/news/toInsert")
    public ModelAndView intoInsert() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        NewsInfoVO newsInfoVO = new NewsInfoVO();
        resultMap.put("news", newsInfoVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/news/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        NewsInfoVO newsInfoVO = newsInfoService.findById(id);
        resultMap.put("news", newsInfoVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/news/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(NewsInfoVO newsInfoVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        String validMsg = newsInfoVO.valid();
        if (StringUtils.isNotBlank(validMsg)) {
            resultMap.put("result", false);
            resultMap.put("message", validMsg);
            return JSONObject.toJSONString(resultMap);
        }

        try {
            Integer affectCount = 0;
            if (newsInfoVO != null && StringUtils.isNotBlank(newsInfoVO.getNewsId())) {
                affectCount = newsInfoService.update(newsInfoVO);
            } else if (newsInfoVO != null) {
                newsInfoVO.setNewsId(UUID.randomUUID().toString());
                newsInfoVO.setCreateUser(seUser.getUserId());
                newsInfoVO.setDataStatus(0);
                newsInfoVO.setNewsStatus(1);
                affectCount = newsInfoService.insert(newsInfoVO);
            }
            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改新闻成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改新闻失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改新闻出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改新闻出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/news/audit", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String audit(String id, Integer status) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            NewsInfoVO newsInfoVO = new NewsInfoVO();

            newsInfoVO.setNewsId(id);

            newsInfoVO.setNewsStatus(status);

            Integer auditCount = newsInfoService.update(newsInfoVO);
            if (auditCount != null && auditCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "审核新闻成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "审核新闻成功失败");
            }
        } catch (Exception e) {
            logger.error("审核新闻成功出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "审核新闻成功出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/news/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = newsInfoService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除新闻成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除新闻失败");
            }
        } catch (Exception e) {
            logger.error("删除新闻出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除新闻出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/uncheck/news/list")
    public ModelAndView queryList(NewsInfoParam newsInfoParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        newsInfoParam.setNewsStatus(2);
        List<NewsInfoVO> dataList = newsInfoService.queryByPage(newsInfoParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", newsInfoParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/admin/news/list")
    public ModelAndView newsManageList(NewsInfoParam newsInfoParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        List<NewsInfoVO> dataList = newsInfoService.queryByPage(newsInfoParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", newsInfoParam);
        return new ModelAndView(ADMIN_MANAGE_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/news/view/{id}")
    public ModelAndView view(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        NewsInfoVO newsInfoVO = newsInfoService.findById(id);
        resultMap.put("news", newsInfoVO);
        resultMap.put("discussType", 5);
        resultMap.put("discussTargetId", newsInfoVO.getNewsId());

        Integer newsType = newsInfoVO.getNewsType();
        if (newsType == null || newsType == 0) {
            newsType = 1;
        }
        NewsInfoVO lastNews = newsInfoService.selectLastOrNextNews("last", newsInfoVO.getCreateTime(), newsType);
        NewsInfoVO nextNews = newsInfoService.selectLastOrNextNews("next", newsInfoVO.getCreateTime(), newsType);
        
        if (lastNews != null) {
            resultMap.put("lastNews", lastNews);
        }
        if (nextNews != null) {
            resultMap.put("nextNews", nextNews);
        }
        return new ModelAndView(VIEW_PAGE, resultMap);
    }
}
